﻿using InternetSpiderLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WeChatGZHTextExtractor.DB;

namespace WeChatGZHTextExtractor.BusinessCreaters
{
    public class BC_NewAccountUrl : IBusinessCreater
    {
        private SceneManager _SceneManager;

        public BC_NewAccountUrl()
        {
            _SceneManager = SingleCase.Get<SceneManager>();
        }

        // 提取远程数据
        public Action Create()
        {
            //var db_context = SingleCase.Get<WxDataContext>();
            var account_service = new BaseService<WXAccountModel>();
            //var model = account_service.Query(context => context.Where(n => n.Monitor).Where(n => n.LastTime + n.Interval < Timestamp.Now).Where(n => string.IsNullOrEmpty(n.Url)).FirstOrDefault());

            var model = account_service.Query(context => context.Where(n => n.Monitor).Where(n => n.LastTime + n.Interval < Timestamp.Now).FirstOrDefault());

            if (model == null)
                return null;

            model.LastTime = Timestamp.Now;
            //db_context.SaveChanges();
            account_service.Change();

            return () =>
            {
                var url = $"http://weixin.sogou.com/weixin?type=1&s_from=input&query={model.WXAccount}&ie=utf8&_sug_=n&_sug_type_=";

                LogHelper.GetInstance().Log(LogType.Info, url);

                var body = HttpHelper.HttpGet(url);

                _SceneManager.TriggerScene(new DataBox()
                    .Set<string>(PublicKey.EventType.EVENT_NAME, PublicKey.EventType.HTTP_GET)
                    .Set(model)
                    .Set<string>(PublicKey.HtmlInfo.URL, url)
                    .Set<string>(PublicKey.HtmlInfo.BODY, body));
            };
        }
    }
}
